import { util } from 'yt-engine'
import { getValueFromConfig, strToArr } from './utils'

const { jsPase } = util

const comLifeStr = 'init,beforeRender,render,afterRender,beforeDestroy,destroy'.split(',')

export function treeEach (data, callback, config = {}) {
  data.forEach(item => {
    let subConfig = config
    // 如果是object节点，则换成object子节点接收数据
    if (item.viewType === 'object') {
      subConfig = subConfig[item.comkey] = {}
    } else {
      callback(item, subConfig)
    }

    if (item.children && item.children.length > 0) {
      return treeEach(item.children, callback, subConfig)
    }
  })

  return config
}

export function getDataFromConfig (config) {
  const initConfig = treeEach(
    config,
    (item, config) => {
      if (item.viewType === 'component') {
        if (item.initClazz) {
          config.initClazz = item.initClazz
        }

        config.type = item.type
        config.clazzType = item.clazzType
      }

      if (item.comkey) {
        if (!comLifeStr.includes(item.comkey)) {
          try {
            config[item.comkey] = jsPase(getValueFromConfig(item))
          } catch (e) {
            console.error(e)
          }
        } else {
          config[item.comkey] = {
            events: strToArr(item.events) || [],
            actionIds: strToArr(item.actionIds) || [],
            providerIds: strToArr(item.providerIds) || [],
            jsHandNames: strToArr(item.jsHandNames) || []
          }
        }
      }
    })

  return initConfig
}

export function parseDocumentToJson (doc) {
  const arr = []

  if (!doc) {
    return arr
  }

  for (const node of doc.children) {
    arr.push(parseToJson(node))
  }

  return arr
}

/**
 *
 * @param { Element } node
 */
 export function parseToJson (node) {
  const obj = {}

  obj.viewType = node.nodeName

  for (let i = 0; i < node.attributes.length; i++) {
    const attr = node.attributes.item(i)

    obj[attr.name] = attr.value
  }

  if (node.children.length > 0) {
    obj.children = []
    for (const child of node.children) {
      obj.children.push(parseToJson(child))
    }
  }

  return obj
}

/**
 * 解析配置文件
 */
 export function normalizeConfig (config) {
  if (typeof config === 'string') {
    config = new DOMParser().parseFromString(config, 'text/xml')

    config = parseDocumentToJson(config)

    return config
  } else if (config instanceof Document) {
    return parseDocumentToJson(config)
  } else {
    return config
  }
}
